const fs = require('fs')
const http = require('http')
const {createProxyMiddleware} = require('http-proxy-middleware')

// 获取导航栏数据
let fn = createProxyMiddleware('/globalinfo',{
    target: 'http://you.163.com/xhr/globalinfo//queryTop.json',
    changeOrigin: true,
    pathRewrite: {
        '/globalinfo': ''
    }
})

// 获取所有商品数据
let fn2 = createProxyMiddleware('/item',{
    target: 'http://you.163.com/xhr/item/listByCategory.json',
    changeOrigin: true,
    pathRewrite: {
        '/item': ''
    }
})

// 创建服务器
http.createServer((req,res)=>{
    // 注册接口
    if(req.url === '/register'){
        //将注册页面的数据转换为字符串
        let str = '';
        req.on('data', chunk => {
            str += chunk.toString()
        })
        req.on('end', () => {
            //将数据转换为对象
            let arr = str.split('&')
            let obj = {}
            arr.forEach(item => {
                let brr = item.split('=')
                obj[brr[0]] = brr[1]
            })
            //读取json文件(buffer)，转换为字符串
            let data = fs.readFileSync('./project/src/json/data.json')
            data = data.toString()
            let pbj = {
                code: 0,
                msg: '用户名被占用了'
            }
            //json文件中没有数据
            if (data === '') {
                data = []
                data.push(obj)
                fs.writeFileSync('./project/src/json/data.json', JSON.stringify(data))
                pbj = {
                    code: 1,
                    msg: '注册成功,请登录'
                }
                res.end(JSON.stringify(pbj))
                return false
            }
            //json文件中有数据
            data = JSON.parse(data)
            //判断此用户是否存在
            let index = data.findIndex(item =>item.username === obj.username)
            //不存在，加入
            if (index < 0) {
                data.push(obj)
                data = JSON.stringify(data)
                fs.writeFileSync('./project/src/json/data.json', data)
                pbj = {
                    code: 1,
                    msg: '注册成功'
                }
                res.end(JSON.stringify(pbj))
            }
            // 找到数据了 - 用户名被占用了
            res.end(JSON.stringify(pbj))
        })
    }else if(req.url === '/login'){
        // 登录接口
        //将登录页面的数据转换为字符串
        let str = '';
        req.on('data', chunk => {
            str += chunk.toString()
        })
        req.on('end', () => {
            //将数据转换为对象
            let arr = str.split('&')
            let obj = {}
            arr.forEach(item => {
                let brr = item.split('=')
                obj[brr[0]] = brr[1]
            })
            //读取json文件(buffer)，转换为字符串
            let data = fs.readFileSync('./project/src/json/data.json')
            data = data.toString()
            data = JSON.parse(data)
            let userInfo = data.find(item=> item.username === obj.username)
            userInfo = JSON.stringify(userInfo)
            let index = data.findIndex(item => item.username === obj.username)
            let pbj = {
                code: 1,
                msg: '登录成功',
                userInfo:userInfo
            }
            if (index < 0) {
                pbj = {
                    code: 3,
                    msg: '用户名不存在，请先注册'
                }
                res.end(JSON.stringify(pbj))
            } else {
                let index1 = data.findIndex(item => item.username === obj.username && item.password === obj.password)
                if (index1 < 0) {
                    pbj = {
                        code: 2,
                        msg: '登陆失败,用户名或密码错误'
                    }
                    res.end(JSON.stringify(pbj))
                }
            }
            res.end(JSON.stringify(pbj))
        })
    }else if(req.url.includes('/globalinfo')){
        fn(req,res)
    }else if(req.url.includes('/item')){
        fn2(req,res)
    }else{
        let data = ''
        if(req.url === '/'){
            data = fs.readFileSync('./project/src/index.html')//首页
        }else if(req.url.endsWith('.html')){//其他页面
            data = fs.readFileSync('./project/src'+req.url)
        }else if(req.url.startsWith('/images')){//图片
            data = fs.readFileSync('./project/src'+req.url)
        }else if(req.url === './daili.js'){//代理
            data = fs.readFileSync('./daili.js')
        }else if(req.url === '/layer/theme/default/layer.css?v=3.5.1'){
            data = fs.readFileSync('./project/src/layer/theme/default/layer.css')
        }else if (req.url.startsWith('/js') && req.url.endsWith('.js')) {
            data = fs.readFileSync('./project/src' + req.url)
        }else{//其他
            data = fs.readFileSync('./project/src'+req.url)
        }
        res.end(data)
    }

}).listen(14000)